<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-09-16 20:47
 *
 * 项目：rm  -  $  - aliminiPay.php
 *
 * 作者：liwei 
 */


namespace modules\levpays\modules\alipay\sdk;

use AlipayTradeCreateRequest;
use AlipayTradePayRequest;
use AlipayTradeQueryRequest;
use AopClient;
use Lev;
use stdClass;

!defined('INLEV') && exit('Access Denied LEV');

class aliminiPay extends Payment
{

    /**
     * 创建订单，统一下单
     * 文档： https://opendocs.alipay.com/apis/api_1/alipay.trade.create/
     * @param $buyer_id  //买家支付宝用户ID。2088开头的16位纯数字，小程序场景下获取用户ID请参考：用户授权;其它场景下获取用户ID请参考：网页授权获取用户信息;注：交易的买家与卖家不能相同。
     * @param $out_trade_no
     * @param $subject
     * @param $total_amount
     * @param string $body
     * @param string $timeout_express
     * @throws \Exception
     *
     * 成功响应：
        {
            "alipay_trade_create_response": {
                "code": "10000",
                "msg": "Success",
                "out_trade_no": "20150423001001",
                "trade_no": "2015042321001004720200028594"
            },
            "sign": "ERITJKEIJKJHKKKKKKKHJEREEEEEEEEEEE"
        }
     * 失败响应：
        {
            "alipay_trade_create_response": {
                "code": "20000",
                "msg": "Service Currently Unavailable",
                "sub_code": "isp.unknow-error",
                "sub_msg": "系统繁忙"
            },
            "sign": "ERITJKEIJKJHKKKKKKKHJEREEEEEEEEEEE"
        }'
     */
    public static function createTrade($buyer_id, $out_trade_no, $subject, $total_amount, $body = '', $timeout_express = '10m') {
        $aop = static::setAopClient(Lev::stripTags(Lev::GPv('appid')));

        $object = new stdClass();
        $object->out_trade_no = $out_trade_no;
        $object->total_amount = $total_amount;
        $object->subject      = $subject;
        $object->buyer_id     = $buyer_id;
        $object->body         = $body;
        $object->timeout_express = $timeout_express;
//        //商品信息明细，按需传入
//        $goodsDetail = [
//            [
//                'goods_id'=>'goodsNo1',
//                'goods_name'=>'子商品1',
//                'quantity'=>1,
//                'price'=>0.01,
//            ],
//        ];
//        $object->goodsDetail = $goodsDetail;
//        //扩展信息，按需传入
//        $extendParams = [
//            'sys_service_provider_id'=>'2088511833207846',
//        ];
//        $object->extend_params = $extendParams;
//        //结算信息，按需传入
//        $settleInfo = [
//            'settle_detail_infos'=>[
//                [
//                    'trans_in_type'=>'defaultSettle',
//                    'amount'=>0.01,
//                ]
//            ]
//        ];
//        $object->settle_info = $settleInfo;
//        //二级商户信息，按需传入
//        $subMerchant = [
//            'merchant_id'=>'2088600522519475',
//        ];
//        $object->sub_merchant = $subMerchant;
//        // 业务参数信息，按需传入
//        $businessParams = [
//            'busi_params_key'=>'busiParamsValue',
//        ];
//        $object->business_params= $businessParams;
//        // 营销信息，按需传入
//        $promoParams = [
//            'promo_params_key'=>'promoParamsValue'
//        ];
//        $object->promoParams = $promoParams;
        $json = json_encode($object);
        $request = new AlipayTradeCreateRequest();
        $request->setNotifyUrl('');
        $request->setBizContent($json);
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode   = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            //echo "成功";
            return Lev::responseMsg(1, '下单成功', [
                'trade_no' => trim($result->$responseNode->trade_no),
                'res' => Lev::objectToArray($result->$responseNode)
            ]);
        } else {
            $res = Lev::objectToArray($result->$responseNode);
            return Lev::responseMsg(-1, '下单失败！'.$res['sub_msg'], ['res'=>$res]);
        }
    }

    /**
     * alipay.trade.pay(统一收单交易支付接口)
     * 文档： https://opendocs.alipay.com/apis/api_1/alipay.trade.pay
     * @param $auth_code
     * @param $out_trade_no
     * @param $subject
     * @param $total_amount
     * @param string $body
     * @param string $timeout_express
     * @throws \Exception
     */
    public static function payTrade($auth_code, $out_trade_no, $subject, $total_amount, $body = '', $timeout_express = '10m') {
        $aop = static::setAopClient();

        $object = new stdClass();
        $object->out_trade_no = $out_trade_no;
        $object->total_amount = $total_amount;
        $object->subject      = $subject;
        $object->scene        = 'bar_code';
        $object->auth_code    = $auth_code;
        $object->body         = $body;
        $object->timeout_express = $timeout_express;

//        //商品信息明细
//        $goodsDetail = [
//            [
//                'goods_id'=>'goodsNo1',
//                'goods_name'=>'子商品1',
//                'quantity'=>1,
//                'price'=>0.01,
//            ],
//        ];
//        $object->goodsDetail = $goodsDetail;
//        //扩展信息
//        $extendParams = [
//            'sys_service_provider_id'=>'2088511833207846',
//        ];
//        $object->extend_params = $extendParams;
//        //结算信息
//        $settleInfo = [
//            'settle_detail_infos'=>[
//                [
//                    'trans_in_type'=>'defaultSettle',
//                    'amount'=>0.01,
//                ]
//
//            ]
//        ];
//        $object->settle_info = $settleInfo;
//        //二级商户信息
//        $subMerchant = [
//            'merchant_id'=>'2088600522519475',
//        ];
//        $object->sub_merchant = $subMerchant;
//        // 业务参数信息
//        $businessParams = [
//            'busi_params_key'=>'busiParamsValue',
//        ];
//        $object->business_params= $businessParams;
//        // 营销信息
//        $promoParams = [
//            'promo_params_key'=>'promoParamsValue'
//        ];
//        $object->promoParams = $promoParams;
//        //返回参数选项
//        $queryOptions =[
//            'fund_bill_list',
//            'voucher_detail_list'
//        ];
//        $object->query_options = $queryOptions;

        $json = json_encode($object);
        //echo $json."<br><br>";
        $request = new AlipayTradePayRequest();
        $request->setBizContent($json);
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if (!empty($resultCode) && $resultCode == 10000) {
            return Lev::responseMsg(1, '成功', [
                'trade_no'=>trim($result->$responseNode->trade_no),
                'res'=>Lev::objectToArray($result->$responseNode)
            ]);
        } else {
            return Lev::responseMsg(-1, '失败', ['res'=>Lev::objectToArray($result->$responseNode)]);
        }
    }

    /**
     * alipay.trade.query(统一收单线下交易查询)
     * 文档： https://opendocs.alipay.com/apis/api_1/alipay.trade.query
     * @param string $out_trade_no
     * @param string $trade_no
     * //商户订单号和支付宝交易号不能同时为空。 trade_no、  out_trade_no如果同时存在优先取trade_no
     * //商户订单号，和支付宝交易号二选一
     * //支付宝交易号，和商户订单号二选一
     * @return array
     */
    public static function queryTrade($out_trade_no = '', $trade_no = '') {
        //$out_trade_no = 'T0000000001630467113';

        $aop = static::setAopClient();

        $object = new stdClass();
        $object->out_trade_no = $out_trade_no;
        $object->trade_no     = $trade_no;
        $json = json_encode($object);
        $request = new AlipayTradeQueryRequest();
        $request->setBizContent($json);
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        $result = Lev::objectToArray($result->$responseNode);//print_r($result);
        if (!empty($resultCode) && $resultCode == 10000) {
            $result['_paySuccess'] = $result['trade_status'] == 'TRADE_SUCCESS' || $result['trade_status'] == 'TRADE_FINISHED' || strpos($result['trade_status'], 'SUCCESS') !== false || strpos($result['trade_status'], 'FINISHED') !== false;
        }
//        else {
//            //return Lev::responseMsg(-1, '失败', Lev::objectToArray($result->$responseNode));
//        }
        return $result;
    }

}